package org.vacoor.xqq.ui.util;

import java.awt.*;
import java.net.URL;

/**
 * 图片加载工具
 * 该工具会等待图片加载完成后才返回
 * <p/>
 * {@link java.awt.Toolkit#getImage(String)} 并不保证图片加载完成,
 * 因此 {@link java.awt.Image#getWidth(java.awt.image.ImageObserver)} 可能不能获取宽度
 *
 * @author: Vacoor
 */
public abstract class ImageLoader {
    private static final Object trackerMonitor = new Object();
    private static MediaTracker tracker;
    private static int trackerId;

    /**
     * 加载图片, 等待延迟加载完毕才返回
     * 该方法调用 {@link Toolkit#getImage(java.net.URL)}, 因此将会存在缓存问题
     *
     * @param url
     * @return
     */
    public static Image getImage(URL url) {
        Image image = Toolkit.getDefaultToolkit().getImage(url);
        ensureImageLoaded(image);
        return image;
    }

    /**
     * 等待延迟加载完成
     *
     * @param image the image
     */
    public static void ensureImageLoaded(Image image) {
        MediaTracker mTracker = getTracker();
        int id = nextId();

        mTracker.addImage(image, id);
        image.getWidth(null);
        try {
            mTracker.waitForID(id, 0);
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted while loading Image");
        }
        mTracker.removeImage(image, id);
    }

    private static int nextId() {
        synchronized (getTracker()) {
            return ++trackerId;
        }
    }

    private static MediaTracker getTracker() {
        if (tracker != null) {
            return tracker;
        }

        synchronized (trackerMonitor) {
            if (tracker == null) {
                tracker = new MediaTracker(new Component() {
                });
            }
        }
        return tracker;
    }

    private ImageLoader() {
    }
}
